// pages/user/index.js
import constant from '../../utils/constant'
import { loginOpenId, getUserInfo } from '../../utils/login'
import api from '../../api/index'

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    basePath: wx.$basePath,
    topHeigth: app.globalData.StatusBar + 10,
    openNickname: false,
    avatar: '',
    nickname: '',
    orangeId: 1,
    sex: '1',
    age: '29岁',
    zodiac: '鼠',
    star: '白羊座'

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  haddleSettings(){
    wx.navigateTo({ url: '/pages/login/settings' })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log(wx.$basePath)
    const userInfo = wx.getStorageSync(constant.USER_INFO)
    
    let age = ''
    if(!wx.$isNull(userInfo.birthday)){
      const uYear = (userInfo.birthday.split('-'))[0]
      const date = new Date()
      const year = date.getFullYear()
      age = year - uYear
    }

    this.setData({
      nickname: userInfo.nickname,
      orangeId: userInfo.orangeId,
      sex: userInfo.sex,
      avatar: userInfo.avatar,
      age: age,
      zodiac: userInfo.zodiac,
      star: userInfo.star
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
		let currentTarbar  = this.getTabBar();
		currentTarbar.setData({
			pageCur: 'user'
		})
  },

  handleChooseAvatar(e){
    api.common.uploadAvatarFile(e.detail.avatarUrl).then((upRes)=>{
      api.user.setAvatar(upRes).then((res)=>{
        if(res.code == 0){
          if(!wx.$isNull(this.data.avatar)){
            api.common.delFile(this.data.avatar)
          }
          this.setData({
            avatar: upRes
          })
          let uInfo = wx.getStorageSync(constant.USER_INFO)
          uInfo.avatar = upRes
          wx.setStorageSync(constant.USER_INFO, uInfo)
        }else{
          api.common.delFile(upRes)
        }
      })

    })
	},

  handleNickname(e){
    const a = e.currentTarget.dataset.a
    if(a=='0' || a== '1'){
      this.setData({
        openNickname: true,
        openTime: new Date().getTime()
      })
    } else if(a=='2'){
      api.user.setProfile({nickname: this.data.nickname})
      this.setData({
        openNickname: false
      })
    } else {
      this.setData({
        openNickname: false
      })
    }
    console.log(e)

  },
  inputNickname(e){
    this.setData({
      nickname: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})